<?php

namespace weixin;

use think\Db;

class TemplateMsg
{
    private $appId = '';
    private $appSecret = '';

    public function __construct($appId = '', $appSecret = '')
    {
        empty($appId) && $this->appId = config('wx.appId');
        empty($appSecret) && $this->appSecret = config('wx.appSecret');
    }

    //检测报告消息
    public function reportMsg($report_id)
    {
        $report = Db::name("shopro_report")->where("id", $report_id)->find();
        if (empty($report)) {
            trace(sprintf('report_msg report_id:%s 不存在', $report_id), 'debug');
            return false;
        }
        $mobile = $report['mobile'];
        /*$user_id = Db::name("user")->where("mobile", $mobile)->value('id');
        if (empty($user_id)) {
            trace(sprintf('report_msg mobile:%s用户不存在', $mobile), 'debug');
            return false;
        }*/
        //支持多人绑定
        $openIds = Db::name('shopro_user_oauth')
            ->where('mobile', $mobile)
            ->where('provider', 'wechat')
            ->where('platform', 'wxOfficialAccount')
            ->column('openid');

        if (empty($openIds)) {
            trace(sprintf('report_msg mobile:%s,openid不存在', $mobile), 'debug');
            return false;
        }
        $template_id = "BVMXEI2IL1nn7gIvTbtpiahKxz1H9FZisugvRY4qHpM";
        $data = array(
            'first' => array('value' => '您好，您的检测报告已出。。', 'color' => '#000000'),
            'thing11' => array('value' => $report['title'], 'color' => '#FF0000'),
            'time4' => array('value' => $report['test_date'], 'color' => '#000000'),
        );

        if (substr($report['pdf'], 0, 4) != 'http') {
            $url = request()->domain() . '/' . ltrim($report['pdf'], '/');
        } else {
            $url = $report['pdf'];
        }

        $res = false;
        foreach ($openIds as $openId) {
            $res = $this->sendTemplateMsg($template_id, $data, $openId, $url);
            trace(sprintf('发送模板消息,id:%s，openid:%s,返回：%s', $report_id, $openId, $res), 'debug');
        }

        return $res;
    }


    // 发送模板消息
    public function sendTemplateMsg($template_id, $data, $touser, $url = '')
    {
        $access_token = $this->getAccessToken();
        $template_msg = array('touser' => $touser, 'template_id' => $template_id, 'data' => $data, "url" => $url);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        return $this->httpPost($url, json_encode($template_msg));
    }

    private function getAccessToken()
    {
        $access_token = cache('jsapi_access_token');
        if (!$access_token) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token ?? '';
            if ($access_token) {
                cache('jsapi_access_token', $access_token, $res->expires_in);
            }
        }
        return $access_token;
    }

    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    private function httpPost($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //不输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }


}